import { debounce as _debounce, throttle as _throttle } from 'lodash';
import Vue from 'vue';
import api from 'src/apis/common';
import store from 'src/store';

//解决IE下NodeList无法调用forEach进行遍历的问题
NodeList.prototype.forEach = Array.prototype.forEach;

export const getAdToken = () => {
  api.getAdToken().then(res => {
    if (res.errorCode === '000000' && res.data && res.data.adToken) {
      store.commit('app/setAdToken', res.data.adToken);
    }
  });
};

/**
 * @description 金额格式化
 * @param {String} str 金额，如：111111
 * @param {String} prefix 金额前缀，如: $、￥
 * @returns {String} $111,111.00
 */
export const moneyFormat = (str, prefix = '') => {
  if (!str) return prefix + '0.00';
  let newStr = str
    .toString()
    .replace(/[^\-+\d.]/g, '')
    .replace(/^[0]*(?=\d+)/g, ''); // 去掉开头多余的0和正负号
  if (
    isNaN(newStr) ||
    newStr === '' ||
    newStr === '0' ||
    newStr.toString() === '0.00'
  ) {
    return prefix + '0.00';
  }
  let newNewStr = '';
  if (newStr.indexOf('.') === -1) {
    newNewStr = newStr + '.00';
  } else {
    newNewStr = Number(newStr).toFixed(2);
  }
  newNewStr = newNewStr.indexOf('.') === 0 ? '0' + newNewStr : newNewStr; //补全小数点前的0
  let newNewNewStr = newNewStr.replace(/(\d)(?=(\d{3})+(\.\d{0,2})?$)/g, '$1,');
  return prefix + newNewNewStr;
};

/**
 * @description 金额格式化逆过程
 * @param {String} str 格式化后的金额字符串，例如： $111,111.00
 * @param {String} prefix 金额前缀，如： $、￥
 * @returns {number} 111111
 */
export const moneyFormattedToNum = (str, prefix = '') => {
  str = (str || '') + '';
  return Number(str.replace(/,/g, '').replace(prefix, ''));
};

/**
 * @description 将数字转化为中文大写，不支持万亿以上的数字
 * @param {String | number} number
 * @returns {String}
 */
export function moneyToCapitalize(number, simple = false) {
  let num = parseFloat(number);
  let strOutput = '';
  let strUnit = simple
    ? '千百十亿千百十万千百十元角分'
    : '仟佰拾亿仟佰拾万仟佰拾元角分';
  const chinese = simple ? '零一二三四五六七八九' : '零壹贰叁肆伍陆柒捌玖';
  num += '00';
  const intPos = num.indexOf('.');
  if (intPos >= 0) {
    num = num.substring(0, intPos) + num.substr(intPos + 1, 2);
  }
  if (num.length > strUnit.length) {
    return number;
  }
  strUnit = strUnit.substr(strUnit.length - num.length);
  for (let i = 0; i < num.length; i++) {
    strOutput +=
      chinese.substr(parseInt(num.substr(i, 1)), 1) + strUnit.substr(i, 1);
  }
  return strOutput
    .replace(/零角零分$/, '整')
    .replace(/零[仟佰拾|千百十]/g, '零')
    .replace(/零{2,}/g, '$1')
    .replace(/零([亿|万])/g, '$1')
    .replace(/零+元/, '元')
    .replace(/亿零{0,3}万/, '亿')
    .replace(/^元/, '零元');
}

/**
 * @description 下载流文件
 * @param {Any} data
 * @param {String} filename
 * @param {String} mime
 * @returns {void}
 */
export function download(data, filename, mime) {
  const mimeList = {
    pdf: 'application/pdf',
    jpg: 'image/jpeg',
    jpeg: 'image/jpeg',
    gif: 'image/gif',
    png: 'image/png',
    doc:
      'application/vnd.openxmlformats-officedocument.wordprocesssingml.document',
    docx:
      'application/vnd.openxmlformats-officedocument.wordprocesssingml.document',
    ppt:
      'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    pptx:
      'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    xls: 'application/vnd.ms-excel',
    xlsx: 'aaplication/vmd.openxmlformats-officedocument.spreadsheetml.sheet',
    zip: 'application/zip',
    rar: 'aaplication/zip',
    bmp: 'image/bmp',
    tif: 'image/tiff'
  };
  const blob = new Blob([data], {
    type: mimeList[mime] || 'application/vnd.ms-excel'
  });
  if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveBlob(blob, filename);
  } else {
    const blobURL = window.URL.createObjectURL(blob);
    const tempLink = document.createElement('a');
    tempLink.style.display = 'none';
    tempLink.href = blobURL;
    tempLink.setAttribute('download', filename);
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank');
    }
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);
    setTimeout(() => {
      window.URL.revokeObjectURL(blobURL);
    }, 50);
  }
}

/**
 * 获取安全localStorage数据
 * @param name storage的key值
 * @param defaultVal storage的默认值
 * @returns {*}
 */
export function safeGetLocalStorage(name = '', defaultVal = '') {
  if (!name) return;
  let localNameDatas;
  const getLocalData = localStorage.getItem(name);
  if (getLocalData && getLocalData !== '[object Object]') {
    if (/^(\[|\{)/.test(getLocalData)) {
      localNameDatas = JSON.parse(getLocalData);
    } else {
      localNameDatas = getLocalData;
    }
  } else {
    localNameDatas = defaultVal;
  }
  return localNameDatas;
}

/**
 * 设置安全localStorage数据
 * @param name
 * @param defaultVal
 */
export function safeSetLocalStorage(name = '', defaultVal = '') {
  if (!name) return;
  let safeValue = defaultVal;
  if (typeof safeValue === 'object') {
    safeValue = JSON.stringify(safeValue);
  }
  localStorage.setItem(name, safeValue);
}

/**
 * @description 银行账号格式化
 * @param {String} value 1111111111111111
 * @returns {String} 1111 1111 1111 1111
 */
export function accountFormat(value) {
  if (!value) return '';
  if (typeof value === 'number') {
    value = value + '';
  }
  let val = value.replace(/[\u4E00-\u9FA5]*\s*/g, '');
  if (!val) return '';
  return val
    .replace(/([A-Za-z]{3}(?=[^\s*]))/g, '$1 ')
    .replace(/([0-9]{4}(?=[^\s*]))/g, '$1 ');
}

/**
 * 设置获取登录状态处理登录超时提示
 * @param val
 * @param type
 */
export function storageLoginStatus(val = '', type = 'set') {
  const { lastLogonTime } = safeGetLocalStorage('userInfo', {});
  let loginTime;
  if (lastLogonTime) {
    const changeTime =
      lastLogonTime.indexOf('-') > -1
        ? lastLogonTime.replace('-', '/')
        : lastLogonTime;
    loginTime = new Date(changeTime).getTime();
  }

  const storageKey = `loginStatus${loginTime}`; // 保存登录状态key
  if (type === 'set') {
    if (!loginTime) return;
    sessionStorage.setItem(storageKey, val);
  } else {
    return sessionStorage.getItem(storageKey);
  }
}

// IE浏览器判断
export const isIE = function () {
  if (!!window.ActiveXObject || 'ActiveXObject' in window) return true;
  return false;
};

export function downloadFile(url, e) {
  e.preventDefault();
  window.open(url);
}

export function debounce(func) {
  return _debounce(func, 1000, {
    leading: true,
    trailing: false
  });
}

export function throttle(func) {
  return _throttle(func, 100, {
    leading: true,
    trailing: true
  });
}

export function formatTime(time) {
  if (time) {
    time = time + '';
    time = time.replace(/\s/g, '');
    if (time.length > 0) {
      return time.replace(
        /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/,
        '$1-$2-$3 $4:$5:$6'
      );
    }
    return time.replace(/^(\d{4})(\d{2})(\d{2})(\d*)$/, '$1-$2-$3');
  } else {
    return time;
  }
}

export const eventBus = new Vue();
